/**
 * Created by liubin on 2014/11/24.
 * 权限验证用
 */
define(['app', 'common/services/Principal'], function (app) {
    "use strict";
    return app.factory('Authorization', function ($rootScope, $state, Principal, $log) {
        return {
            authorize: function () {
                // 验证
                return Principal.identity().then(function () {
                        var isAuthenticated = Principal.isAuthenticated();
                        // 如果路由有限定权限，通过权限来控制是否能够访问
                        if ($rootScope.toState.data.roles && $rootScope.toState.data.roles.length > 0 && !Principal.isInAnyRole($rootScope.toState.data.roles)) {
                            if (isAuthenticated) $state.go('lock'); // user is signed in but not authorized for desired state
                            else {
                                // user is not authenticated. stow the state they wanted before you
                                // send them to the signin state, so you can return them when you're done
                                $rootScope.returnToState = $rootScope.toState;
                                $rootScope.returnToStateParams = $rootScope.toStateParams;

                                // now, send them to the signin state so they can log in
                                $state.go('login');
                            }
                        }
                    });
            }
        };
    });
});